package com.mars.mongodemo.demo;

import com.mars.mongodemo.tools.MongoDBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * author by: mars
 * Date: 2020/3/31 14:45
 * Description:
 */
@Service
public class UserService {

    @Autowired
    private MongoDBUtil mongoDBUtil;
    
    public String saveObj(UserInfo userInfo) {
        mongoDBUtil.save(userInfo);
        return "temp ok";
    }

    // 查询所有
    public List<UserInfo> findAll(){
        return mongoDBUtil.findAll(UserInfo.class);
    }

    // 根据用户名称查询
    public List<UserInfo> findUserName(String name){
        return mongoDBUtil.find(UserInfo.class,new String[]{"username"},new String[]{name});
    }

    // 更新用户信息
    public String updateUserInfo(UserInfo userInfo){
        // 查询条件
        //Query query = new Query(Criteria.where("id").is(userInfo.getId()));
        // 更新数据
        //Update update = new Update().set("password",userInfo.getPassword())
        //        .set("username",userInfo.getUsername());
        mongoDBUtil.updateMulti("id",userInfo.getId(),
                new String[]{"password","username"},new String[]{userInfo.getPassword(),userInfo.getUsername()},"");//更新查询返回结果集的全部
        //mongoDBUtil.updateFirst(query,update,UserInfo.class);//更新查询返回结果集的第一条
        //mongoDBUtil.upsert(query,update,UserInfo.class);//更新对象不存在则添加
        return "ok";
    }

    // 删除对象
    public String deleteUserInfo(UserInfo userInfo){
        mongoDBUtil.remove(userInfo);//更新查询返回结果集的全部
        return "ok";
    }
}
